package top.lyc829.zzl_android.ui.team;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.textview.badge.Badge;
import com.xuexiang.xui.widget.textview.badge.BadgeView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Response;
import okhttp3.internal.Util;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.TeamFragmentBinding;
import top.lyc829.zzl_android.logic.bean.LiveEventMsg;
import top.lyc829.zzl_android.logic.bean.MsgNumberBean;
import top.lyc829.zzl_android.logic.bean.MyTeamState;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.TeamSimpleBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.custom_view.seach.OnSearchListener;
import top.lyc829.zzl_android.ui.index.chooseLocation.ChooseLocationActivity;
import top.lyc829.zzl_android.ui.login.LoginActivity;
import top.lyc829.zzl_android.ui.main.LazyFragment;
import top.lyc829.zzl_android.ui.main.MainViewModel;
import top.lyc829.zzl_android.ui.message.MessageActivity;
import top.lyc829.zzl_android.ui.team.add_team.AddTeamActivity;
import top.lyc829.zzl_android.ui.team.my_team.MyTeamActivity;
import top.lyc829.zzl_android.ui.team.team_detail.TeamDetailActivity;
import top.lyc829.zzl_android.ui.thing.dynamic.DynamicRecyclerViewAdapter1;

public class TeamFragment extends LazyFragment {

    private TeamViewModel mViewModel;
    private MainViewModel mainViewModel;
    private TeamFragmentBinding binding;
    private TeamRecyclerAdapter adapter;
    TitleBar.ImageAction imageAction, teamAction;
    private PageInfo teamPage;

    private String searchContent = "";

    Badge badge;

    public static TeamFragment newInstance() {
        return new TeamFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = TeamFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(TeamViewModel.class);
        mainViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        teamPage = new PageInfo();

        LiveEventBus
                .get("team_change", Integer.class)
                .observeSticky(this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (integer.equals(1)) {
                            refresh();
                        }
                    }
                });

        TitleBar.ActionList actions = new TitleBar.ActionList();

        imageAction = new TitleBar.ImageAction(R.drawable.ic_baseline_email_24) {
            @Override
            public void performAction(View view) {
                startActivity(new Intent(getActivity(), MessageActivity.class));
            }
        };
        teamAction = new TitleBar.ImageAction(R.drawable.ic_baseline_add_team_24) {
            @Override
            public void performAction(View view) {
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                Intent intent;
                if (mViewModel.getMyTeamStateLiveData().getValue() == null) {
                    intent = new Intent(getActivity(), AddTeamActivity.class);
                } else if (mViewModel.getMyTeamStateLiveData().getValue().getApplyState().equals("1")) {
                    new MaterialDialog.Builder(getContext())
                            .title("提示")
                            .content("您已申请了活动，请耐心等待")
                            .positiveText("关闭")
                            .negativeText("取消申请")
                            .onNegative((dialog, which) -> {
                                Network.quitTeam(mViewModel.getMyTeamStateLiveData().getValue().getTeamId(),
                                        Utils.getUserId(), new HttpUtil.MyCallback() {
                                            @Override
                                            public void success(Response res) throws IOException {
                                                String resStr = res.body().string();
                                                ResultBean<Void> resultBean = JsonUtilNew.fromJsonObject(resStr, Void.class);
                                                if (resultBean.getCode().equals(200)) {
                                                    getActivity().runOnUiThread(() -> {
                                                        Utils.showToast("取消成功");
                                                        mViewModel.getMyTeamIdFromServer(Utils.getUserId());
                                                    });

                                                } else {
                                                    failed(new IOException(resStr));
                                                }
                                            }

                                            @Override
                                            public void failed(IOException e) {
                                                Utils.showToastSync("操作失败");
                                                Utils.Sout(e.getMessage());
                                            }
                                        });
                            })
                            .show();
                    return;
                } else {
                    intent = new Intent(getActivity(), MyTeamActivity.class);
                    intent.putExtra("teamId", mViewModel.getMyTeamStateLiveData().getValue().getTeamId());
                    //intent.putExtra("apply_state", teamState.getApplyState());
                }
                startActivity(intent);

            }
        };

        actions.add(imageAction);
        actions.add(teamAction);
        binding.mTitleBarTeam.addActions(actions);

        binding.mTitleBarTeam.setLeftImageResource(R.drawable.indicator_dowm);
        binding.mTitleBarTeam.setLeftText("地点");
        binding.mTitleBarTeam.setLeftClickListener(v -> {
            Intent intent = new Intent(getActivity(), ChooseLocationActivity.class);
            startActivity(intent);
        });

        badge = new BadgeView(getContext())
                .bindTarget(binding.mTitleBarTeam.getViewByAction(imageAction))
                .setBadgeGravity(Gravity.TOP | Gravity.END)
                .setExactMode(false)
                .setBadgeBackgroundColor(0xdfFFC364)
                .setGravityOffset(-3, 8, true)
                .setBadgePadding(1, true)
                .setBadgeNumber(0);


        observe();
        initRecyclerAdapter();



    }

    @Override
    public void onResume() {
        super.onResume();

        if (Utils.isLogin()) {
            mViewModel.getMyTeamIdFromServer(Utils.getUserId());
        } else {
//            ((ImageView)binding.mTitleBarTeam.getViewByAction(teamAction))
//                    .setImageResource(R.drawable.ic_baseline_add_team_24);
            mViewModel.getMyTeamStateLiveData().setValue(null);
        }

        if (Utils.isStringEmpty(Utils.getValueFromSp("location"))) {
            binding.mTitleBarTeam.setLeftText("地点");
        } else {
            binding.mTitleBarTeam.setLeftText(Utils.getValueFromSp("location"));
        }

//        String location = Utils.getValueFromSp("location");
//        if (!Utils.isStringEmpty(location) && !location.equals(binding.mTitleBarTeam.getLeftText().toString())) {
//            refresh();
//            binding.mTitleBarTeam.setLeftText(location);
//        }

        //msgNumberService();
        mainViewModel.updateMsgNumber();


    }

    @Override
    public void lazyInit() {
        binding.swipeLayout.setRefreshing(true);
        refresh();
        initRefreshLayout();
        initLoadMore();
        msgNumberService();
        clickListener();
    }

    private void clickListener() {

        adapter.setOnItemClickListener((adapter1, view, position) -> {
            int temId = adapter.getData().get(position).getId();
            Intent intent = new Intent(getActivity(), TeamDetailActivity.class);
            intent.putExtra("team_id", temId);
            startActivity(intent);
        });

        binding.searchTeam.setOnClickListener(v -> {
            binding.searchTeam.setFocus();
        });

//        binding.searchTeam.setOnSearchListener(content -> {
//            Utils.Sout("搜索触发");
//            Utils.showToast("搜索触发");
//            searchContent = content;
//            refresh();
//        });

        binding.btnSearchTeam.setOnClickListener(v -> {
            searchContent = binding.searchTeam.getSearchContent().trim();
            binding.swipeLayout.setRefreshing(true);
            refresh();

        });

        LiveEventBus
                .get("index_refresh", LiveEventMsg.class)
                .observe(this, liveEventMsg -> {
                    String location = Utils.getValueFromSp("location");
                    binding.swipeLayout.setRefreshing(true);
                    refresh();
                    binding.mTitleBarTeam.setLeftText(location.length() > 0 ? location : "地点");
                });

    }

    private void observe() {
        mViewModel.getTeamSimplesLiveData().observe(getViewLifecycleOwner(), teamSimpleBeans -> {

            binding.swipeLayout.setRefreshing(false);
            adapter.getLoadMoreModule().setEnableLoadMore(true);
            if (teamPage.isFirstPage()) {
                adapter.setList(teamSimpleBeans);
            } else {
                adapter.addData(teamSimpleBeans);
            }

            if (teamSimpleBeans == null || teamSimpleBeans.size() < PageInfo.MAX_ITEM) {
                adapter.getLoadMoreModule().loadMoreEnd();
            } else {
                teamPage.nextPage();
                // 加载完成，等待下一次加载
                adapter.getLoadMoreModule().loadMoreComplete();
            }
            if (teamPage.getPage() == 1 && (teamSimpleBeans == null || teamSimpleBeans.size() == 0)) {
                Utils.showToast("没有更多内容");
            }
        });

//        mViewModel.getMyTeamIdLiveData().observe(getViewLifecycleOwner(), integer -> {
//            if (integer > 0) {
//                ((ImageView)binding.mTitleBarTeam.getViewByAction(teamAction))
//                        .setImageResource(R.drawable.ic_baseline_my_team_24);
//            } else {
//                ((ImageView)binding.mTitleBarTeam.getViewByAction(teamAction))
//                        .setImageResource(R.drawable.ic_baseline_add_team_24);
//            }
//        });

        mViewModel.getMyTeamStateLiveData().observe(getViewLifecycleOwner(), myTeamState -> {

            if (myTeamState == null) {
                ((ImageView)binding.mTitleBarTeam.getViewByAction(teamAction))
                        .setImageResource(R.drawable.ic_baseline_add_team_24);
                return;
            }

            if (myTeamState.getApplyState().equals("3")) {
                ((ImageView)binding.mTitleBarTeam.getViewByAction(teamAction))
                        .setImageResource(R.drawable.ic_baseline_add_team_24);
                return;
            }

            if (myTeamState.getTeamId() > 0) {
                ((ImageView)binding.mTitleBarTeam.getViewByAction(teamAction))
                        .setImageResource(R.drawable.ic_baseline_my_team_24);
            } else {
                ((ImageView)binding.mTitleBarTeam.getViewByAction(teamAction))
                        .setImageResource(R.drawable.ic_baseline_add_team_24);
            }
        });


    }

    private void initRecyclerAdapter() {
        adapter = new TeamRecyclerAdapter();
        binding.teamRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.teamRecyclerview.setAdapter(adapter);
        adapter.setAnimationEnable(true);   // recyclerview加载动画
    }


    /**
     * 初始化加载更多
     */
    private void initLoadMore() {
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                request();
            }
        });
        adapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void initRefreshLayout() {
        binding.swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        binding.swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

    }

    /**
     * 刷新
     */
    private void refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        adapter.getLoadMoreModule().setEnableLoadMore(false);
        mViewModel.getMyTeamIdFromServer(Utils.getUserId());
        //msgNumberService();
        mainViewModel.updateMsgNumber();
        // 下拉刷新，需要重置页数
        teamPage.reset();
        request();
    }

    private void request() {
        mViewModel.getTeams(teamPage.getPage(), Utils.getValueFromSp("location"), searchContent);
    }


    private void msgNumberService() {
        // 观察消息个数
        mainViewModel.getMsgNumberLiveData().observe(getViewLifecycleOwner(), msgNumberBean -> {
            badge.setBadgeNumber(msgNumberBean.getTotalNum());
        });
    }


}